import 'package:acgn_pioneer/plugin/dialog/src/constants.dart';
import 'package:acgn_pioneer/plugin/dialog/src/dialog.dart';
import 'package:acgn_pioneer/widgets/reader/services/sr_comment.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';

import '../../public.dart';
import '_index.dart';
import 'events/_index.dart';
import 'mixins/widget_base.dart';

/// 右侧显示交互按钮
class ReaderRightMenu extends StatefulWidget {
  ReaderRightMenu({Key key}) : super(key: key);

  @override
  ReaderRightMenuState createState() => new ReaderRightMenuState();
}

class ReaderRightMenuState extends State<ReaderRightMenu>
    with ReaderWidgetBase, TickerProviderStateMixin {
  AnimationController controller;
  Animation animation;
  ReaderCommentService readerCommentService = ReaderCommentService();

  bool isShow = true; // 是否显示菜单
  var sub; // 关闭菜单
  var subRun; // 阅读页开启
  var subScroll;
  int commentCount = 0;
  double scrollOffset = 0;

  @override
  void initState() {
    super.initState();

    sub = readerPage.bus.on<ReaderCloseMenuEvent>().listen((event) {
      if (!event.isToggle && !isShow) {
        return;
      }
      // toggleAnimation();
    });

    subRun = readerPage.bus.on<ReaderRunEvent>().listen((event) {
      getCommentCount();
    });

    subScroll = readerPage.bus.on<ReaderMoveEvent>().listen((event) {
      scrollOffset = event.offset;
    });

    controller = AnimationController(
        duration: const Duration(milliseconds: 500), vsync: this);
    animation =
        Tween(begin: Offset.zero, end: Offset(0, 1)).animate(controller);
  }

  // 获取评论总数
  getCommentCount() async {
    commentCount = await readerCommentService.getNewCommentCount(
        readModel.currentChapter.comicModel.id, 0);
    setState(() {});
  }

  @override
  void dispose() {
    sub.cancel();
    subRun.cancel();
    subScroll.cancel();

    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var current = readModel.currentChapter;
    userRecord = Provider.of<UserRecordProvider>(context);

    if (current == null) {
      return Container();
    }

    return Positioned(
        bottom: 110,
        right: 0,
        child: SliderAnimation(animation: animation, child: _body(current)));
  }

  Widget _body(ChapterModel current) {
    TextStyle style = TextStyle(color: Colors.white);
    SizedBox spitBox = SizedBox(height: 8);
    return Container(
      padding: EdgeInsets.all(Rem(20)),
      width: 84,
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GestureDetector(
              child: Column(
                children: [
                  Image.asset(AppConfig.ASSETS_PATH + getCollectIcon(current)),
                  Text('追更', style: style)
                ],
              ),
              onTap: () {
                readerPage.bus.fire(ReaderMoveEvent(0));
                return;
                addUserCollect(current);
              },
            ),
            spitBox,
            GestureDetector(
              child: Column(
                children: [
                  Image.asset(AppConfig.ASSETS_PATH + 'comment.png'),
                  Text(commentCount.toString(), style: style)
                ],
              ),
              onTap: () {
                showMaterialModalBottomSheet(
                    enableDrag: false,
                    context: context,
                    builder: (context) => Container(
                          height: 600,
                          child: ReaderComment(
                              chapterModel: current,
                              isComicType: scrollOffset < 300),
                        ));
              },
            ),
            spitBox,
            GestureDetector(
              onTap: () {
                doShare(current);
              },
              child: Column(
                children: [
                  Image.asset(AppConfig.ASSETS_PATH + 'share.png'),
                  Text(
                      readModel.currentChapter.comicModel.shareCount.toString(),
                      style: style)
                ],
              ),
            )
          ],
        ),
      ]),
      decoration: BoxDecoration(boxShadow: [
        BoxShadow(
            color: Color.fromARGB(20, 0, 0, 0),
            offset: Offset(0.0, 15.0),
            blurRadius: 15.0,
            spreadRadius: 1.0)
      ]),
    );
  }

  getCollectIcon(ChapterModel chapter) {
    return hasCollected(chapter) ? 'dianzan_cli.png' : 'dianzan.png';
  }

  hasCollected(ChapterModel chapter) {
    var index = userRecord.userCollect
        .indexWhere((item) => item.comicId == chapter.comicModel.id);
    return index != -1;
  }

  void doShare(ChapterModel current) {
    ACGNDialog(context,
        alignment: Alignment.bottomCenter,
        clipBehavior: Clip.antiAlias,
        backgroundColor: Color(0xff1B1B26),
        transition: DialogTransition(
          duration: Duration(milliseconds: 300),
          builder: (context, animation, secondaryAnimation, child) {
            return FractionalTranslation(
              translation: Offset(0, 1 - animation.value),
              child: child,
            );
          },
        ),
        shape: RoundedRectangleBorder(
          side: BorderSide.none,
        ),
        barrier: DialogBarrier(
            barrierDismissible: true,
            barrierColor: ColorUtil.rgba(0, 0, 0, 0.25)),
        body: DialogBody(
            padding: EdgeInsets.all(0),
            isScorll: false,
            content: StatefulBuilder(builder: (context, setState) {
              return ShareComponent(
                  popTitle: '分享《${current.comicModel.name}》赚积分（0/3）',
                  title: '这个可以免费看《${current.comicModel.name}》',
                  imageUrl:
                      'https://shareact.50manhua.com/2020/0820_inviteFriend/img/icon.218b45b5.png',
                  url: getShareUrl(current),
                  desc: '全免漫画App，终生免费看漫画');
            }))).show();
  }

  // 规则：  md5('comic_id='comic_id+'&chapter_id='+chapter_id+''+salt)
  // 例： md5(comic_id=25934&chapter_id=19026318erciyuan2020) 结果为： 81981ff0d7eca941809fdf9e2fb500c8
  getShareUrl(ChapterModel chapter) {
    var comicId = chapter.comicModel.id;
    var chapterId = chapter.id;
    var link = 'comic_id=$comicId&chapter_id=$chapterId';
    var token = CryptoUtil.md5Encrypt(link + AppConfig.QUEST_KEY);
    return AppConfig.SHARE_COMIC_URL + link + '&share_token=$token';
  }

  addUserCollect(ChapterModel chapter) async {
    var hasC = hasCollected(chapter);
    await this
        .readerPage
        .chapterService
        .addUserCollect(chapter, user.uid, hasC ? 'del' : 'add');
    if (hasC) {
      userRecord.userCollect
          .removeWhere((element) => element.comicId == chapter.comicModel.id);
    } else {
      userRecord.userCollect.add(UserCollectItemModel(chapter.comicModel.id));
      ACGN.toast.message('追更成功');
    }

    setState(() {});
  }

  /// 动画执行
  toggleAnimation() {
    if (isShow) {
      controller.forward();
    } else {
      controller.reverse();
    }
    isShow = !isShow;
  }
}
